class Encrypt {
  key = ""
  constructor(key) {
    this.key = key
  }

  // 加密字符串
  encode(str) {
    let asciiArr = str.split('').map(char => char.charCodeAt(0))
    let encodedArr = asciiArr.map((ascii, index) => ascii ^ this.key.charCodeAt(index % this.key.length))
    let encodedStr = encodedArr.map(ascii => String.fromCharCode(ascii)).join('')
    return encodedStr
  }
  // 解密字符串
  decode(str) {
    let asciiArr = str.split('').map(char => char.charCodeAt(0))
    let decodedArr = asciiArr.map((ascii, index) => ascii ^ this.key.charCodeAt(index % this.key.length))
    let decodedStr = decodedArr.map(ascii => String.fromCharCode(ascii)).join('')
    return decodedStr
  }

  // 生成随机密钥
  generateKeyPair() {
    let key = (Math.random() * 36).toString(36).substr(2, 16)
    let asciiArr = key.split('').map(char => char.charCodeAt(0))
    let encodedArr = asciiArr.map((ascii, index) => ascii ^ this.key.charCodeAt(index % this.key.length))
    let encodedStr = encodedArr.map(ascii => String.fromCharCode(ascii)).join('')
    return encodedStr
  }

  // 通过密钥加密字符串
  encodeWithKey(str, key) {
    let asciiArr = str.split('').map(char => char.charCodeAt(0))
    let encodedArr = asciiArr.map((ascii, index) => ascii ^ key.charCodeAt(index % key.length))
    let encodedStr = encodedArr.map(ascii => String.fromCharCode(ascii)).join('')
    return encodedStr
  }

  // 通过密钥解密字符串
  decodeWithKey(str, key) {
    let asciiArr = str.split('').map(char => char.charCodeAt(0))
    let decodedArr = asciiArr.map((ascii, index) => ascii ^ key.charCodeAt(index % key.length))
    let decodedStr = decodedArr.map(ascii => String.fromCharCode(ascii)).join('')
    return decodedStr
  }

}

const key = "8888"
const en = new Encrypt(key)
// 固定秘钥加密解密
const code = en.encode("qwere生日歌儿童儿童儿童人 wo收到让更多人他儿童画儿童合同热源荣誉统计开头语加快7UI8看687看 儿童画人员已经5y7ujk5y7yuk他哟屁话35平日更好v去诶铺如果他8237495同样rld")
console.log(code)
const decode = en.decode(code)
console.log(decode)


// 用随机秘钥加密解密
const keyPair = en.generateKeyPair()
const newCode = en.encodeWithKey("qwere生日歌儿童儿童儿童人 wo收到让更多人他儿童画儿童合同热源荣誉统计开头语加快7UI8看687看 儿童画人员已经5y7ujk5y7yuk他哟屁话35平日更好v去诶铺如果他8237495同样rld", keyPair)
console.log(newCode)
const newDecode = en.decodeWithKey(newCode, keyPair)
console.log(newDecode)